import requests
from prettytable import *
import datetime
import mysql


#获取a股个股最新历史数据，最新在最前，每行为一天的数据
#format:DATE,收盘价,最高价,最低价,涨跌额,涨跌幅,换手率,成交量,成交金额,总市值,流通市值
#return：iget抓取到的行数
def get_stock_163_history(code):
    #编码转换
    org_code=code
    ncode=code.replace("sh","0")
    nncode=ncode.replace("sz","1")
    
    #抓取到当前日期
    latest_date = datetime.date.today()
    time_str=latest_date.strftime("%Y%m%d")
    url='http://quotes.money.163.com/service/chddata.html?code='+nncode+'&start=20160101&end='+time_str+'&fields=PCHG;TCLOSE'
    print(url)
    iget=0
    r=requests.get(url)
    line=r.text.replace("日期,股票代码,名称,涨跌幅,收盘价\r\n", "")

    records = []
    record = {'Code': code}
    # for o in json_obj['Data']['LSJZList']:
    #     record['Date'] = o['FSRQ']
    #     record['NetAssetValue'] = o['DWJZ']
    #     record['ChangePercent'] = o['JZZZL']
    #     records.append(record.copy())

    for r in line.split("\r\n"):
        if r == "":
            continue

        arr = r.replace("'", "").split(",")
        record['Date'] = arr[0]
        record['NetAssetValue'] = arr[4]
        record['ChangePercent'] = arr[3]
        records.append(record.copy())
        # print(r)

    return records



if __name__ == "__main__":
    # print(get_stock_163_history('sh000300'))
    
    mysql.updateFundValue('sh000300', get_stock_163_history('sh000300'))





